/*  

Copyright [2013-2014] eBay Software Foundation

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/
package models.data.providers;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import models.data.AggregateData;
import models.data.AggregationValueMetadata;
import models.data.JsonResult;
import models.rest.beans.responses.AggregationResponse;
import models.utils.AgentUtils;
import models.utils.DateUtils;
import models.utils.VarUtils;
/**
 * 
 * @author ypei
 *
 */
public class AgentCommadProviderHelperAggregation {

	/**
	 * 20131110 derived from aggregation pie chart API.
	 * 
	 * 
	 * 
	 * @param nodeGroupType
	 * @param agentCommandType
	 * @param timeStamp
	 * @param rawDataSourceType
	 * @param aggrRule
	 * @param textOnly
	 * @return
	 */
	public static String genAggregationResultTextGivenAggregationType(
			String nodeGroupType, String agentCommandType, String timeStamp,
			String rawDataSourceType, String aggrRule) {

		String patternStr = "N/A";

		String responseText = "genAggregationResultGivenAggregationType started";

		try {

			AgentDataAggregator ada = AgentDataAggregator.getInstance();
			AgentDataProvider adp = AgentDataProvider.getInstance();
			Map<String, String> rulesMap = adp.aggregationMetadatas;
			// 20130610: fix null

			if (aggrRule == null) {
				aggrRule = VarUtils.AGGREGATION_DEFAULT_METRIC;
			}
			patternStr = rulesMap
					.get((aggrRule == null || aggrRule.length() == 0) ? VarUtils.AGGREGATION_DEFAULT_METRIC
							: aggrRule);
			AggregateData aggregateData = ada.aggregateMetricsWithGroupingNew(
					nodeGroupType, agentCommandType, timeStamp,
					rawDataSourceType, patternStr);


			List<AggregationValueMetadata> avmList = aggregateData
					.getResponseToMetadataList();

			Map<String, String> aggregationMap = aggregateData
					.getValueCountAggregationMap();

			AggregationResponse aggregationResponse = new AggregationResponse(aggregationMap, avmList);
			
			responseText = AgentUtils.renderJson(aggregationResponse);
			
		} catch (Throwable t) {

			responseText = "Error in genAggregationResultGivenAggregationType for nodeGroupType"
					+ nodeGroupType
					+ " error: "
					+ t.getLocalizedMessage()
					+ "  at time: " + DateUtils.getNowDateTimeStrSdsm();
			models.utils.LogUtils.printLogError(responseText);
		}// end catch

		return responseText;
	}

}
